/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>
#include "iservice_registry.h"
#include "i_sle_host.h"
#include "sle_ssap_client_impl.h"
#include "sle_common_config.h"
#include "sle_connect_config.h"
#include "sle_hilog.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
SleSsapClient::SleSsapClientImpl::SleSsapClientImpl(const SleUuid &uuid) : clientId_(0)
{
    SLE_LOGI("SleSsapClientImpl In");
    Uuid cUuid(uuid);
    clientUuid_= cUuid;

    callbackImpl_ = new SleSsapClientCallbackStubImpl(*this);
    SLE_ASSERT_AND_RETURN_LOG(callbackImpl_, "callbackImpl null error!");

    auto resetCallback = [this](const wptr<IRemoteObject> &remote) { this->ResetService(remote); };
    deathRecipient_ = new SleDeathRecipient(resetCallback);
    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");

    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "get proxy error!");
}

SleSsapClient::SleSsapClientImpl::~SleSsapClientImpl()
{
    SLE_LOGI("~SleSsapClientImpl In");
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "ssap client proxy null error!");
    if (isRegistered_) {
        SleErrorCode ret = proxy_->UnregisterSsapClient(clientId_, callbackImpl_);
        SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "unregister ssap client failed!");
    }
}

void SleSsapClient::SleSsapClientImpl::GetProxy()
{
    if (proxy_) {
        return;
    }
    sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    SLE_ASSERT_AND_RETURN_LOG(samgr, "no samgr error!");

    sptr<IRemoteObject> hostRemote = samgr->GetSystemAbility(KH_SLE_SERVICE_SYS_ABILITY_ID_);

    SLE_ASSERT_AND_RETURN_LOG(hostRemote, "no remote error!");
    sptr<ISleHost> hostProxy = iface_cast<ISleHost>(hostRemote);
    SLE_ASSERT_AND_RETURN_LOG(hostProxy, "host proxy null error!");

    sptr<IRemoteObject> remote = hostProxy->GetSleServerRemote(SLE_SSAP_CLIENT_SERVER);
    SLE_ASSERT_AND_RETURN_LOG(remote, "no remote error!");

    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");
    SLE_ASSERT_AND_RETURN_LOG(!((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))),
        "Failed to add death recipient");

    proxy_ = iface_cast<ISleSsapClient>(remote);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no announce proxy error!");
    SleErrorCode ret = proxy_->RegisterSsapClient(clientUuid_, clientId_, callbackImpl_);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "register ssap client failed!");
    isRegistered_ = true;
    SLE_LOGI("GetProxy success");
}

void SleSsapClient::SleSsapClientImpl::ResetService(const wptr<IRemoteObject> &remote)
{
    SLE_ASSERT_AND_RETURN_LOG(remote != nullptr, "remote null error!");
    std::lock_guard<std::mutex> lock(mutexProxy_);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no proxy error!");
    sptr<IRemoteObject> serviceRemote = proxy_->AsObject();
    if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
        serviceRemote->RemoveDeathRecipient(deathRecipient_);
        proxy_ = nullptr;
        int tryTime = 5;
        while ((!proxy_) && tryTime > 0) {
            sleep(GET_PROXY_SLEEP_SEC);
            tryTime--;
            GetProxy();
        }
    }
}

SleErrorCode SleSsapClient::SleSsapClientImpl::CheckOperation()
{
    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_RET_LOG(proxy_, SLE_ERR_INTERNAL_WRONG, "proxy null error!");
    return SLE_NO_ERROR;
}

SleSsapClient::SleSsapClient(const SleUuid &uuid)
{
    SLE_LOGI("SleSsapClient In");
    SLE_ASSERT_AND_RETURN_LOG(Uuid::CheckSleUuid(uuid) == SLE_NO_ERROR, "check client app uuid failed!");
    pimpl_ = std::make_unique<SleSsapClientImpl>(uuid);
    SLE_ASSERT_AND_RETURN_LOG(pimpl_, "pimpl null error!");
}

SleSsapClient::~SleSsapClient()
{
    SLE_LOGI("~SleSsapClient In");

}

SleErrorCode SleSsapClient::FindSsapStructure(uint16_t connectId, const ClientFindStructure &param)
{
    SLE_LOGD("FindSsapStructure In");
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SleErrorCode ret = SsapClientFindStructure::CheckClientFindStructure(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    SsapClientFindStructure params(param);
    ret = pimpl_->proxy_->FindSsapStructure(pimpl_->clientId_, connectId, params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "find structure failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::ReadRequestByUuid(uint16_t connectId, const ClientReadReqByUUID &param)
{
    SLE_LOGD("FindSsapStructure In");
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SleErrorCode ret = SsapClientReadReqByUUID::CheckClientReadReqByUUID(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    SsapClientReadReqByUUID params(param);
    ret = pimpl_->proxy_->ReadRequestByUuid(pimpl_->clientId_, connectId, params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "read request by uuid failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::ReadRequest(uint16_t connectId, uint16_t handle, SleSsapPropertyType type)
{
    SLE_LOGD("ReadRequest In");
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(handle != 0, SLE_ERR_INTERNAL_WRONG, "handle error!");
    SLE_ASSERT_AND_RETURN_RET_LOG((type >= SLE_SSAP_PROPERTY_TYPE && type <= SLE_SSAP_DESCRIPTOR_TYPE_RFU) ||
        type == SLE_SSAP_DESCRIPTOR_TYPE_CUSTOM, SLE_ERR_INTERNAL_WRONG, "param request type error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    ret = pimpl_->proxy_->ReadRequest(pimpl_->clientId_, connectId, handle, type);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "read request failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::WriteRequest(uint16_t connectId, const ClientWriteParam &param)
{
#if 0
    SLE_LOGD("WriteRequest In");
#endif
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SleErrorCode ret = SsapClientHandleValue::CheckClientWriteParam(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    SsapClientHandleValue params(param);
    ret = pimpl_->proxy_->WriteRequest(pimpl_->clientId_, connectId, params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "write request failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::WriteCommand(uint16_t connectId, const ClientWriteParam &param)
{
#if 0
    SLE_LOGD("WriteCommand In");
#endif
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SleErrorCode ret = SsapClientHandleValue::CheckClientWriteParam(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    SsapClientHandleValue params(param);
    ret = pimpl_->proxy_->WriteCommand(pimpl_->clientId_, connectId, params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "write command failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::ExchangeInfo(uint16_t connectId, const SsapMtuInfo &info)
{
    SLE_LOGD("ExchangeInfo In");
    SLE_ASSERT_AND_RETURN_RET_LOG(connectId < SLE_MAX_CONNECT_ID_NUM,
        SLE_ERR_INTERNAL_WRONG, "param connect id error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    ret = pimpl_->proxy_->ExchangeInfo(pimpl_->clientId_, connectId, info.mtuSize, info.version);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "exchange info failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::RegisterClientCallback(std::shared_ptr<SleSsapClientCallback> callback)
{
    SLE_LOGD("RegisterClientCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Register(callback), SLE_ERR_FAILED,
        "register client callback failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleSsapClient::UnregisterClientCallback(std::shared_ptr<SleSsapClientCallback> callback)
{
    SLE_LOGD("UnregisterClientCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Unregister(callback), SLE_ERR_FAILED,
       "unregister client callback failed!");
    return SLE_NO_ERROR;
}
} // SleStandard
} // NearLink
} // OHOS